<template>
  <view class="face-capture-container">
    <view class="camera-wrapper">
      <camera 
        device-position="front" 
        flash="off" 
        class="camera"
        @error="handleCameraError"
      ></camera>
      
      <view class="capture-overlay">
        <view class="tips-container">
          <text class="tips-text">请将面部对准屏幕中央，点击录制按钮</text>
          <text class="tips-subtext">保持正脸，确保光线充足</text>
        </view>
    
      </view>
      
     
    </view>
    
    <view class="controls">
      <button 
        class="capture-btn" 
        @tap="startRecord"
        :disabled="isRecording || isCapturing"
      >
        {{ isRecording ? '录制中...' : (isCapturing ? '处理中...' : '录制') }}
      </button>
      
    
    </view>
    
    <view class="preview" v-if="tempImagePath">
      <image :src="tempImagePath" mode="aspectFit" class="preview-image"></image>
      <view class="preview-actions">
        <button class="retake-btn" @tap="retake">重拍</button>
        <button class="confirm-btn" @tap="confirmImage">确认</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isCapturing: false,
      isRecording: false,
      countdown: 3,
      error: null,
      showTips: true,
      cameraContext: null,
      recordTimeout: null
    }
  },
  
  onLoad() {
    this.cameraContext = uni.createCameraContext()
  },
  
  onUnload() {
    this.clearTimers()
  },
  
  methods: {
    async startRecord() {
      if (this.isRecording || this.isCapturing) return
      
      this.isRecording = true
      this.countdown = 3
      this.error = null
      
      try {
        const res = await new Promise((resolve, reject) => {
          this.cameraContext.startRecord({
            success: () => {
              // 开始3秒倒计时
              this.startCountdown()
              
              // 3秒后停止录制
              this.recordTimeout = setTimeout(() => {
                this.stopRecord().then(resolve).catch(reject)
              }, 3000)
            },
            fail: reject
          })
        })
        
      } catch (error) {
        this.handleRecordError(error)
      }
    },
    
    startCountdown() {
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      },
      
      // 添加录制成功的提示
      showSuccessTips() {
        uni.showToast({
          title: '录制完成',
          icon: 'success',
          duration: 1000
        })
      },
      
      // 修改stopRecord方法，添加成功提示
      stopRecord() {
        if (!this.isRecording) return
        
        this.clearTimers()
        
        return new Promise((resolve, reject) => {
          this.cameraContext.stopRecord({
            success: (res) => {
              this.isRecording = false
              this.isCapturing = false
              
              // 显示录制成功提示
              this.showSuccessTips()
              
              // 延迟返回，让用户看到提示
              setTimeout(() => {
                // 获取上一个页面实例
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                
                if (prevPage) {
                  // 触发自定义事件，传递录像结果
                  const eventChannel = this.getOpenerEventChannel()
                  if (eventChannel && eventChannel.emit) {
                    eventChannel.emit('faceCaptureComplete', {
                      success: true,
                      videoPath: res.tempVideoPath,
                      duration: 3,
                      timestamp: Date.now(),
                      size: res.size || 0
                    })
                  } else {
                    // 兼容旧版本
                    prevPage.$vm.handleFaceCaptureComplete && prevPage.$vm.handleFaceCaptureComplete({
                      success: true,
                      videoPath: res.tempVideoPath,
                      duration: 3,
                      timestamp: Date.now(),
                      size: res.size || 0
                    })
                  }
                }
                
                // 返回上一页
                uni.navigateBack()
              }, 1000)
              
              resolve(res)
            },
            fail: (error) => {
              this.handleRecordError(error)
              reject(error)
            }
          })
        })
      },
    
    clearTimers() {
      if (this.recordTimeout) {
        clearTimeout(this.recordTimeout)
        this.recordTimeout = null
      }
    },
    
    handleRecordError(error) {
        this.error = error.errMsg || '录制失败，请重试'
        this.isRecording = false
        this.isCapturing = false
        
        let errorMessage = '录制失败，请重试'
        if (error.errMsg) {
          if (error.errMsg.includes('auth')) {
            errorMessage = '相机权限未开启，请在设置中允许访问相机'
          } else if (error.errMsg.includes('cancel')) {
            errorMessage = '录制已取消'
          } else if (error.errMsg.includes('network')) {
            errorMessage = '网络连接异常，请检查网络后重试'
          } else {
            errorMessage = error.errMsg
          }
        }
        
        uni.showModal({
          title: '录制失败',
          content: errorMessage,
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#007AFF'
        })
        console.error('录制错误:', error)
      },
      
      handleCameraError(e) {
        let errorMessage = '无法打开相机，请检查权限设置'
        if (e.detail && e.detail.errMsg) {
          if (e.detail.errMsg.includes('auth')) {
            errorMessage = '相机权限未开启，请在系统设置中允许应用访问相机'
          } else if (e.detail.errMsg.includes('system')) {
            errorMessage = '相机启动失败，请重启应用后重试'
          }
        }
        
        uni.showModal({
          title: '相机错误',
          content: errorMessage,
          showCancel: false,
          confirmText: '去设置',
          success: (res) => {
            if (res.confirm) {
              // 引导用户到设置页面（微信小程序环境）
              uni.openSetting({
                success: (settingRes) => {
                  console.log('用户设置结果:', settingRes)
                }
              })
            }
          }
        })
        console.error('相机错误:', e)
      },
    
    toggleTips() {
      this.showTips = !this.showTips
    }
  }
}
</script>

<style lang="scss" scoped>
.face-capture-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #000;
}

.camera-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.camera {
  width: 100%;
  height: 100%;
}

.capture-overlay {
  position: absolute;
  top: -900rpx;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
}

.tips-container {
  background-color: rgba(0, 0, 0, 0.6);
  padding: 30rpx 40rpx;
  border-radius: 20rpx;
  text-align: center;
}

.tips-text {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.tips-subtext {
  color: #ccc;
  font-size: 28rpx;
  display: block;
}

.capture-frame {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400rpx;
  height: 800rpx;
  border: 4rpx solid #fff;
  border-radius: 20rpx;
  box-shadow: 0 0 0 2000rpx rgba(0, 0, 0, 0.5);
}

.controls {
  position: absolute;
  bottom: 100rpx;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 30rpx;
}

.capture-btn {
  width: 180rpx;
  height: 180rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #4CAF50, #81C784);
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #fff;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 8rpx 24rpx rgba(76, 175, 80, 0.3);
  backdrop-filter: blur(10rpx);
}

.capture-btn:active {
  transform: scale(0.95);
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.2);
  background: linear-gradient(135deg, #43A047, #66BB6A);
}

.capture-btn[disabled] {
  opacity: 0.6;
  background: linear-gradient(135deg, #A5D6A7, #C8E6C9);
  box-shadow: 0 4rpx 12rpx rgba(165, 214, 167, 0.2);
  color: rgba(255, 255, 255, 0.7);
}

.toggle-tips-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.preview {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  display: flex;
  flex-direction: column;
}

.preview-image {
  flex: 1;
  width: 100%;
  height: 100%;
}

.preview-actions {
  position: absolute;
  bottom: 100rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 0 100rpx;
}

.retake-btn,
.confirm-btn {
  width: 200rpx;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
}

.retake-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.confirm-btn {
  background-color: #007AFF;
  color: #fff;
}
</style>